//
//  MainViewController.swift
//  Weibo10
//
//  Created by Leon on 15/10/14.
//  Copyright © 2015年 Leon. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {
    
    // MARK: - 监听方法
    @objc private func plusButtonClick() {
        
        var vc: UIViewController
        if UserAccountViewModel.shareAccount.userLogon {
            vc = ComposeViewController()
        } else {
            vc = OAuthViewController()
        }
        
        let nav = UINavigationController(rootViewController: vc)
        presentViewController(nav, animated: true, completion: nil)
    }

    // MARK: - 视图的生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        
        addChildViewControllers()
        
        addPlusButton()
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(true)
        
        tabBar.bringSubviewToFront(plusButton)
    }
    
    // MARK: - 懒加载
    private lazy var plusButton: UIButton = UIButton(imageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button")
    
    

}

// MARK: - 设置界面
extension MainViewController {
    
    /// 添加撰写按钮
    private func addPlusButton() {
        tabBar.addSubview(plusButton)
        
        let count = childViewControllers.count
        
        let w = tabBar.bounds.width / CGFloat(count) - 1
        
        plusButton.frame = CGRectInset(tabBar.bounds, w * 2, 0)
        
        plusButton.addTarget(self, action: "plusButtonClick", forControlEvents: .TouchUpInside)
    }
    
    /**
    添加所有子控制器
    */
    private func addChildViewControllers() {
        
        addChildViewController(HomeViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(MessageTableViewController(), title: "消息中心", imageName: "tabbar_message_center")
        addChildViewController(UIViewController())
        addChildViewController(DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
    }
    
    /**
    添加控制器
    
    - parameter vc:        子控制器
    - parameter title:     控制器名称
    - parameter imageName: 图片名称
    */
    private func addChildViewController(vc:UIViewController, title: String, imageName:String) {
        
        // 设置标题
        vc.title = title
        
        // 设置tabBarItem的背景
        vc.tabBarItem.image = UIImage(named: imageName)
        
        // 包装一个导航控制器 并 添加到tabBarVC
        addChildViewController(UINavigationController(rootViewController: vc))
        
    }
}
